package zoujt.controller;



import zoujt.entitys.User;
import zoujt.service.UserService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/*
 * @auth zoujt
 * @date 2021/2/25
 * @Description
 */
@WebServlet("/sys/user/*")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserService();


    //查询所有
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        ArrayList<User> users = userService.listAll();
        ServletContext servletContext = getServletContext();
        servletContext.setAttribute("listUser",users);
        req.getRequestDispatcher("/userListAll.jsp").forward(req,resp);
    }
    //添加用户
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        User user = new User();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String deptId = req.getParameter("deptId");
        String sex = req.getParameter("sex");

        user.setUsername(username);
        user.setPassword(password);
        user.setDeptId(Integer.valueOf(deptId));
        user.setSex(Integer.valueOf(sex));
        userService.userAdd(user);
        resp.sendRedirect("/sys/user/list");

    }
    //删除用户
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String id = req.getParameter("id");
        userService.userDelete(Integer.valueOf(id));

        req.getRequestDispatcher("/sys/user/list").forward(req,resp);
    }

    //修改用户
    protected void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String id = req.getParameter("id");
        User user = userService.updateById(Integer.valueOf(id));
        req.setAttribute("user",user);
        req.getRequestDispatcher("/userUpdate.jsp").forward(req,resp);
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        User user = new User();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String deptId = req.getParameter("deptId");
        String sex = req.getParameter("sex");
        String id = req.getParameter("id");

        user.setUsername(username);
        user.setPassword(password);
        user.setDeptId(Integer.valueOf(deptId));
        user.setSex(Integer.valueOf(sex));
        user.setId(Integer.valueOf(id));
        userService.userUpdate(user);
        req.getRequestDispatcher("/sys/user/list").forward(req,resp);

    }
}
